﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
namespace FocusOnTerrain
{
    public class FocusOnDB
    {
        public static HeightMap RandomMap(int sizex, int sizey)
        {
            HeightMap ret = null;
            if (sizex > 0 && sizey > 0)
            {
                ret = new HeightMap(sizex, sizey);
                int seed=(int)(DateTime.Now.Ticks % Int32.MaxValue);
                Random rand = new Random(seed);
                for (int x = 0; x < sizex; x++)
                {
                    for (int y = 0; y < sizey; y++)
                    {
                        float z = (float)rand.NextDouble();
                        z = 2 * (0.5f - z);
                        ret[x, y] = z;
                    }
                }
            }
            return ret;
        }
        public static HeightMap Load(string file, IDictionary<string, string> options)
        {
            HeightMap ret = null;
            FileStream stream = new FileStream(file, FileMode.Truncate);
            GZipStream zip = new GZipStream(stream, CompressionMode.Decompress);
            BinaryReader reader = new BinaryReader(zip, Encoding.Unicode);
            int version = reader.ReadInt32();
            int sizex = reader.ReadInt32();
            int sizey = reader.ReadInt32();
            ret = new HeightMap(sizex, sizey);
            for (int x = 0; x < sizex; x++)
            {
                for (int y = 0; y < sizey; y++)
                {
                    ret[x, y] = reader.ReadSingle();
                }
            }
            return ret;
        }
        public static void Save(string file, HeightMap map)
        {
            Save(file, map, new Dictionary<string, string>());
        }
        public static void Save(string file, HeightMap map, IDictionary<string, string> options)
        {
            FileStream stream = new FileStream(file, FileMode.Create);
            GZipStream zip = new GZipStream(stream, CompressionMode.Compress);
            BinaryWriter writer = new BinaryWriter(zip,Encoding.Unicode);
            writer.Write(1);//版本号
            writer.Write(map.SizeX);//维度X
            writer.Write(map.SizeY);//维度Y
            for (int x = 0; x < map.SizeX; x++)
            {
                for (int y = 0; y < map.SizeY; y++)
                {
                    writer.Write(map[x, y]);
                }
            }
            writer.Close();
        }
    }
}
